package net.expectx.pay.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * @author lijian
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {
    /**
     *
     *                获取验证码图片
     * @author         ccg
     * @param         request
     * @param         response
     * @return
     * @throws         IOException
     */
    @ApiOperation(value = "获取验证码图片")
    @RequestMapping("getCaptchaCode")
    public void getCaptchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        outputCaptcha(request, response);
    }

    /**
     *
     *                前端输入的验证码与生成的对比
     * @author         ccg
     * @param         request
     * @param         response
     * @param         captchaCode
     * Created        2017年1月17日 下午5:34:23
     */
    @RequestMapping("checkCaptchaCode")
    public void checkCaptchaCode(HttpServletRequest request, HttpServletResponse response,@RequestParam("captchaCode") String captchaCode){
        System.out.println("页面输入验证码===="+captchaCode);

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String generateCode =(String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        String result = "";
        if(generateCode.toLowerCase().equals(captchaCode.toLowerCase())){
            result = "验证成功";
        }else{
            result = "输入错误";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
    }
    private static final char[] CHARS = {
            '1', '2', '3', '4', '5', '6', '7', '8',  '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    private static Random random = new Random();

    private static String getRandomString() {
        StringBuffer buffer = new StringBuffer();
        for(int i = 0; i < 6; i++) {
            buffer.append(CHARS[random.nextInt(CHARS.length)]);
        }
        return buffer.toString();
    }

    private static Color getRandomColor() {
        return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
    }

    private static Color getReverseColor(Color c) {
        return new Color(255, 255, 255);
    }

    public static void outputCaptcha(HttpServletRequest request, HttpServletResponse response)throws IOException {

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String randomString = getRandomString();
        System.out.println(randomString);
        request.getSession(true).setAttribute("KAPTCHA_SESSION_KEY", randomString);
        int width = 100;
        int height = 35;

        Color color = getRandomColor();
        Color reverse = getReverseColor(color);

        BufferedImage bi = new BufferedImage(width, height,  BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16));
        g.setColor(reverse);
        g.fillRect(0, 0, width, height);
        g.setColor(color);
        g.drawString(randomString, 18, 20);
        for (int i = 0, n = random.nextInt(100); i < n; i++) {
            g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
        }

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        out.flush();
    }
}
